<style>
    .columnList {border-collapse: collapse;}
    .columnList th {background-color: #eee;}
    .columnList th,.columnList td {padding: 5px 10px;border: 1px solid #ddd;line-height: 24px;text-align: center;}
</style>
<button class="btn btn-success" onclick="test()">test</button>
<div class="box box-info">
    <div class="box-header with-border">
        <h3 class="box-title">创建</h3>

        <div class="box-tools">
            <div class="btn-group pull-right" style="margin-right: 10px">
                <a href="{{admin_url('goods')}}" class="btn btn-sm btn-default"><i class="fa fa-list"></i>&nbsp;列表</a>
            </div> <div class="btn-group pull-right" style="margin-right: 10px">
                <a class="btn btn-sm btn-default form-history-back"><i class="fa fa-arrow-left"></i>&nbsp;返回</a>
            </div>
        </div>
    </div>
    <!-- /.box-header -->
    <!-- form start -->
    <form action="{{admin_url('goods')}}" method="post" accept-charset="UTF-8" class="form-horizontal">

        <div class="box-body">

            <div class="fields-group">
                <div class="form-group">

                    <label for="name" class="col-sm-2 control-label">名称</label>

                    <div class="col-sm-8">
                        <div class="input-group">

                            <span class="input-group-addon"><i class="fa fa-pencil"></i></span>

                            <input type="text" id="name" name="name" value="" class="form-control name" placeholder="输入 名称" />


                        </div>


                    </div>
                </div>
                <div class="form-group">

                    <label for="desc" class="col-sm-2 control-label">描述</label>

                    <div class="col-sm-8">

                        <textarea name="desc" class="form-control" rows="5" placeholder="输入 描述"  ></textarea>


                    </div>
                </div>

                <div class="form-group">

                    <label for="img_urls" class="col-sm-2 control-label">图片</label>

                    <div class="col-sm-8">

                        <input type="file" class="img_urls" name="img_urls[]" value="" multiple="1" />


                    </div>
                </div>

                <div class="form-group">

                    <label for="category_id" class="col-sm-2 control-label">分类名称</label>

                    <div class="col-sm-8">
                        <input type="hidden" name="category_id"/>

                        <select class="form-control category_id" style="width: 100%;" name="category_id"  >
                            <option value=""></option>
                            @foreach($categoriesOptions as $categoryId=>$categoriesOption)
                            <option value="{{$categoryId}}">{{$categoriesOption}}</option>
                            @endforeach
                        </select>


                    </div>
                </div>

                <div class="form-group">

                    <label for="attribute" class="col-sm-2 control-label">商品规格</label>

                    <div class="col-sm-8">

                        <div style="margin-bottom: 10px">
                            <button id="add_attr_button" type="button" onclick="addAttrDiv()" class="btn btn-success">添加规格</button>
                            <!--                            <button style="display: none" id="remove_attr_button" type="button" onclick="removeAttrDiv()" class="btn btn-danger">去除规格</button>-->
                        </div>

                        <div id="attr_div" class="row">

                        </div>
                    </div>
                </div>

                <div id="attr_detail" class="form-group">
                    <label class="col-sm-2 control-label">商品规格详细</label>
                    <div id="createTable"></div>
                </div>

                <div class="form-group">

                    <label for="detail" class="col-sm-2 control-label">详情</label>

                    <div class="col-sm-8">
                        <textarea class="form-control" id="detail" name="detail" placeholder="输入 详情"  ></textarea>


                    </div>
                </div>



            </div>

        </div>
        <!-- /.box-body -->
        <div class="box-footer">

            {{ csrf_field() }}
            <div class="col-md-2">

            </div>
            <div class="col-md-8">

                <div class="btn-group pull-right">
                    <button type="submit" class="btn btn-info pull-right" data-loading-text="<i class='fa fa-spinner fa-spin '></i> 提交">提交</button>
                </div>

                <div class="btn-group pull-left">
                    <button type="reset" class="btn btn-warning">撤销</button>
                </div>

            </div>

        </div>


        <!-- /.box-footer -->
    </form>
</div>
<template id="attr-tpl">
    <div style="width:auto" class="col-md-2">
        <div class="box box-success">
            <div class="box-header with-border">
                <h3 class="box-title">规格</h3>

                <div class="box-tools pull-right">
                    <button onclick="removeAttrDiv(this)" type="button" class="btn btn-box-tool"><i class="fa fa-times"></i></button>
                </div>
                <!-- /.box-tools -->
            </div>
            <!-- /.box-header -->
            <div class="box-body">
                <label class="control-label">规格的名称</label>
                <div class="">
                    <input onchange="refreshAttrs()" style="width:auto" type="text" data-index="__index__" class="form-control attr-name" placeholder="规格名">
                </div>
                <div>
                    <label class="control-label">规格的值<button onclick="addAttrValue(this)" type="button" class="btn btn-success">+</button></label>
                    <div style="display: flex">
                        <input onchange="refreshAttrs()" style="width: auto" type="text" class="form-control attr-value-__index__" placeholder="规格值"><button onclick="removeAttrValue(this)" type="button" class="btn btn-danger">-</button>
                    </div>
                </div>
            </div>
            <!-- /.box-body -->
        </div>
        <!-- /.box -->
    </div>

</template>

<script>
    //生成表格相关函数
    $.fn.mergeCell = function (options) {
        return this.each(function () {
            var cols = options.cols;
            for (var i = cols.length - 1; cols[i] != undefined; i--) {
                mergeCell($(this), cols[i]);
            }
            dispose($(this));
        })
    };
    
    var attrs = [];
    addAttrDiv();
    $('form').on('submit', function (e) {
        e.preventDefault(); // prevent native submit
        $(this).ajaxSubmit({
            success: function (res) {
                if (!res.status) {
                    layer.msg(res.message);
                }
            }
        });
    });

    //重新存储规格名和规格值
    function refreshAttrs() {
        attrs = [];
        $('.attr-name').each(function () {
            var attrName = $(this).val();
            var attrIndex = $(this).data('index');
            attrs[attrIndex] = {};
            attrs[attrIndex].name = attrName;
            attrs[attrIndex].values = [];
            $('.attr-value-' + attrIndex).each(function () {
                attrs[attrIndex].values.push($(this).val());
            });
        });
        console.log(attrs);
    }

    function test() {
        var arrayTile = [];
        var arrayInfor = [];
        var arrayColumn = [];
        var columnIndex = 0;
        refreshAttrs();

        $.each(attrs, function (index, value) {
            arrayTile.push(value.name);
            arrayInfor[index] = [];
            $.each(value.values, function (i, v) {
                arrayInfor[index].push(v);
            });
        });
        $.each(arrayTile, function (i, item) {
            arrayColumn.push(columnIndex++);
        });
        console.log(arrayTile);
        console.log(arrayInfor);
        $('#createTable').html('');
        var table = $('<table id="process" class="columnList"></table>');
        table.appendTo($('#createTable'));
        var thead = $('<thead></thead>');
        thead.appendTo(table);
        var trHead = $('<tr></tr>');
        trHead.appendTo(thead);
        // 创建表头
        var str = '';
        $.each(arrayTile, function (index, item) {
            str += '<th width="100">' + item + '</th>';
        })
        str += '<th  width="200">价格</th><th width="100">操作</th>';
        trHead.append(str);
        var tbody = $('<tbody></tbody>');
        tbody.appendTo(table);

        var zuheDate = doExchange(arrayInfor);
        if (zuheDate.length > 0) {
            //创建行
            $.each(zuheDate, function (index, item) {
                var td_array = item.split(',');
                var tr = $('<tr></tr>');
                tr.appendTo(tbody);
                var str = '';
                $.each(td_array, function (i, values) {
                    str += '<td>' + values + '</td>';
                });
                str += '<td ><input name="Txt_PriceSon" class="inpbox inpbox-mini" type="text"></td>';
                str += '<td ><a href="#">删除</a></td>';
                tr.append(str);
            });
        }

        //结束创建Table表
        arrayColumn.pop(); //删除数组中最后一项
        //合并单元格
        $(table).mergeCell({
            // 目前只有cols这么一个配置项, 用数组表示列的索引,从0开始
            cols: arrayColumn
        });
    }

    function addAttrDetail() {

        $('#attr-group-tpl').html().replace('__attr_group__');
        $('#attr_detail').append($('#attr-detail-tpl').html().replace(/__index__/g, 1));
    }

    //添加规格div
    function addAttrDiv() {
        $('#attr_div').append($('#attr-tpl').html().replace(/__index__/g, $('#attr_div').children("div").length).replace(/__index1__/g, $('#attr_div').children("div").length + 1));
        if ($('#attr_div').children("div").length == 3) {
            $('#add_attr_button').attr('disabled', true);
        }
    }
    //移除规格div
    function removeAttrDiv(ele) {
        if ($('#attr_div').children("div").length == 1) {
            return;
        }
        $(ele).parent().parent().parent().parent().remove();
        if ($('#attr_div').children("div").length < 3) {
            $('#add_attr_button').attr('disabled', false);
        }
    }
    //为某个规格div添加规格值
    function addAttrValue(ele) {
        var div = $(ele).parent().next();
        $(ele).parent().parent().append(div.prop("outerHTML"));
    }

    //移除规格值input
    function removeAttrValue(ele) {
        var div = $(ele).parent();
        if ($(ele).parent().parent().children('div').length > 1) {
            div.remove();
        }
        refreshAttrs();
    }

    //生成表格相关函数
    function doExchange(doubleArrays) {
        // 二维数组，最先两个数组组合成一个数组，与后边的数组组成新的数组，依次类推，知道二维数组变成以为数组，所有数据两两组合
        var len = doubleArrays.length;
        if (len >= 2) {
            var arr1 = doubleArrays[0];
            var arr2 = doubleArrays[1];
            var len1 = arr1.length;
            var len2 = arr2.length;
            var newLen = len1 * len2;
            var temp = new Array(newLen);
            var index = 0;
            for (var i = 0; i < len1; i++) {
                for (var j = 0; j < len2; j++) {
                    temp[index++] = arr1[i] + ',' + arr2[j];
                }
            }
            var newArray = new Array(len - 1);
            newArray[0] = temp;
            if (len > 2) {
                var _count = 1;
                for (var i = 2; i < len; i++) {
                    newArray[_count++] = doubleArrays[i];
                }
            }
            return doExchange(newArray);
        } else {
            return doubleArrays[0];
        }
    }

    //生成表格相关函数
    function mergeCell($table, colIndex) {
        $table.data('col-content', ''); // 存放单元格内容
        $table.data('col-rowspan', 1); // 存放计算的rowspan值 默认为1
        $table.data('col-td', $()); // 存放发现的第一个与前一行比较结果不同td(jQuery封装过的), 默认一个"空"的jquery对象
        $table.data('trNum', $('tbody tr', $table).length); // 要处理表格的总行数, 用于最后一行做特殊处理时进行判断之用
        // 进行"扫面"处理 关键是定位col-td, 和其对应的rowspan
        $('tbody tr', $table).each(function (index) {
            // td:eq中的colIndex即列索引
            var $td = $('td:eq(' + colIndex + ')', this);
            // 获取单元格的当前内容
            var currentContent = $td.html();
            // 第一次时走次分支
            if ($table.data('col-content') == '') {
                $table.data('col-content', currentContent);
                $table.data('col-td', $td);
            } else {
                // 上一行与当前行内容相同
                if ($table.data('col-content') == currentContent) {
                    // 上一行与当前行内容相同则col-rowspan累加, 保存新值
                    var rowspan = $table.data('col-rowspan') + 1;
                    $table.data('col-rowspan', rowspan);
                    // 值得注意的是 如果用了$td.remove()就会对其他列的处理造成影响
                    $td.hide();
                    // 最后一行的情况比较特殊一点
                    // 比如最后2行 td中的内容是一样的, 那么到最后一行就应该把此时的col-td里保存的td设置rowspan
                    // 最后一行不会向下判断是否有不同的内容
                    if (++index == $table.data('trNum'))
                        $table.data('col-td').attr('rowspan', $table.data('col-rowspan'));
                }
                // 上一行与当前行内容不同
                else {
                    // col-rowspan默认为1, 如果统计出的col-rowspan没有变化, 不处理
                    if ($table.data('col-rowspan') != 1) {
                        $table.data('col-td').attr('rowspan', $table.data('col-rowspan'));
                    }
                    // 保存第一次出现不同内容的td, 和其内容, 重置col-rowspan
                    $table.data('col-td', $td);
                    $table.data('col-content', $td.html());
                    $table.data('col-rowspan', 1);
                }
            }
        })
    }
    
    //生成表格相关函数
    function dispose($table) {
        $table.removeData();
    }
    $(function () {
        $('.form-history-back').on('click', function (event) {
            event.preventDefault();
            history.back(1);
        });
        $("input.img_urls").fileinput({"overwriteInitial": false, "initialPreviewAsData": true, "browseLabel": "\u6d4f\u89c8", "showRemove": false, "showUpload": false, "deleteExtraData": {"img_urls": "_file_del_", "_file_del_": "", "_token": "OyIyJ11musURIWOwFpxxcgDMHpjOhksHWbbOKuEN", "_method": "PUT"}, "deleteUrl": "http:\/\/111.231.118.189:8080\/admin\/", "allowedFileTypes": ["image"]});
        $(".category_id").select2({"allowClear": true, "placeholder": "\u5206\u7c7b\u540d\u79f0"});
        CKEDITOR.replace('detail');
    });

</script>